package com.example.controller.pc;

import com.example.common.result.Result;
import com.example.entity.dto.pc.JHDCFXlistDto;
import com.example.entity.dto.pc.JHDCFXlistItem;
import com.example.entity.vo.pc.JHDCFXlistVo;
import com.example.entity.vo.pc.JHListItem;
import com.example.mapper.pc.WLPHZBMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/api/JHDCFX")
@Api(tags = "计划达成分析")
public class JHDCFXController {

    @Autowired
    private WLPHZBMapper mapper;

    @ApiOperation("列表")
    @PostMapping("list")
    public Result<PageInfo<JHDCFXlistVo>> list(@RequestBody JHDCFXlistDto dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        if (StringUtils.isNotEmpty(dto.getSpecification())) {
            dto.setSpecification(dto.getSpecification().replaceAll("([\\[\\]*+_%/^])", "/$1"));
        }
        List<JHDCFXlistVo> list = mapper.JHDCFXlist(dto);
        List<String> params = new ArrayList<>();
        for (JHDCFXlistVo vo : list) {
            params.add(new String(vo.getWorkSingle() + "^" + vo.getWorkNo() + "^" + vo.getProcessNo()));
//            vo.setDateData(mapper.JHDCFXlistItem(params, dto.getStartTime(), dto.getEndTime()));
        }
        List<JHDCFXlistItem> item = mapper.JHDCFXlistItem(params, dto.getStartTime(), dto.getEndTime());
        Map<String, List<JHListItem>> map = new HashMap<>();
        for(JHDCFXlistItem t : item) {
            List<JHListItem> listItems = map.get(t.getKey());
            if(listItems == null) {
                listItems = new ArrayList<>();
            }
            listItems.add(new JHListItem(t.getDate(), t.getPlanNum(), t.getCompletedNum()));
            map.put(t.getKey(), listItems);
        }
        for (Map.Entry<String, List<JHListItem>> entry : map.entrySet()) {
            List<JHListItem> value = entry.getValue();
            value.sort(Comparator.comparing(t -> t.getDate()));
//            System.out.println("Key: " + key + ", Value: " + value);
        }
        for (JHDCFXlistVo vo : list) {
            vo.setDateData(map.get(vo.getWorkSingle().trim() + "^" + vo.getWorkNo().trim() + "^" + vo.getProcessNo().trim()));
        }
        PageInfo<JHDCFXlistVo> pageInfo = new PageInfo(list);
        return Result.success(pageInfo);
    }

}
